package com.leo.voice;

import java.util.ArrayList;
import java.util.List;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class DesktopGridAdapter extends BaseAdapter{
	private static String TAG="DesktopGridAdapter";
	private VoiceApplication mApplication;
	private PackageManager mPackageManager;
	private LayoutInflater mLayoutInflater;   //this class should create instance for the layout description
	private List<DesktopGridItem> mItems;
	public DesktopGridAdapter(Context c, List<ResolveInfo> appInfos ){
		mApplication = (VoiceApplication) ((VoiceDesktop)c).getApplication();
		mLayoutInflater = (LayoutInflater) ((VoiceDesktop)c).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mPackageManager = ((VoiceDesktop)c).getPackageManager();
		mItems = new ArrayList<DesktopGridItem>();
		
		DesktopGridItem item;
		for( ResolveInfo info : appInfos ){
			item = new DesktopGridItem();
			item.setAppIcon(info.activityInfo.loadIcon(mPackageManager));
			item.setAppName((String) info.activityInfo.loadLabel(mPackageManager));
			Log.i(TAG, info.activityInfo.packageName+" " +info.getClass().getName());
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			item.setAppLauncher(intent);
			
			mItems.add(item);
		}
	}
	
	public int getCount() {
		// TODO Auto-generated method stub
		return mItems.size();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mItems.get(position);
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View v;
		ViewHolder holder;
		List<ApplicationInfo> allInfo;
		if(convertView == null){
			v = mLayoutInflater.inflate(R.layout.grid_item, null);
			holder = new ViewHolder(v);
			v.setTag(holder);
		}else{
			v = convertView;
			holder = (ViewHolder) v.getTag();
		}
		DesktopGridItem item = mItems.get(position);
		holder.appName.setText(item.getAppName());
		holder.appIcon.setImageDrawable(item.getAppIcon());
		return v;
	}

	class ViewHolder{
		public TextView appName;
		public ImageView appIcon;
		
		public ViewHolder(View v){
			appName = (TextView) v.findViewById(R.id.grid_item_text);
			appIcon = (ImageView) v.findViewById(R.id.grid_item_image);
		}
	}
}
